using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Comdiv.Extensions;
using Comdiv.Model;
using Comdiv.Model.Interfaces;
using Comdiv.Logging;
using Comdiv.Application;
using Comdiv.Persistence;
using Comdiv.Inversion;
using Comdiv.Security.Acl;
using Comdiv.Conversations;
using Comdiv.IO;
using Comdiv.Security;


namespace wikiviewer.Controllers{
    public class WikiListFormatter:IWikiFormatter{
        public int Idx { get; set; }

        private int currentlevel;
        private bool isinlist;
        private StringBuilder builder;
        Stack<string> openedPool = new Stack<string>();

        public string Process(string current){
            builder = new StringBuilder();
            var stringreader = new StringReader(current);
            string line = "";
            while(null!=(line=stringreader.ReadLine())){
                var state = getliststate(line);
                if(state.islist){
                    isinlist = true;
                    if(currentlevel<state.level){
                        string e = state.isordered ? "ol" : "ul";
                        openedPool.Push("</"+e+">");
                        builder.Append("<" + e + ">");
                        
                    }
                    if(currentlevel > state.level){
                        while (openedPool.Count> state.level){
                            builder.Append(openedPool.Pop());
                        }
                    }
                    currentlevel = state.level;
                    builder.Append("<li>");
                    builder.Append(state.rest);
                    builder.AppendLine("</li>");

                }else{
                    if(isinlist){
                        closelist();
                        
                    }
                    builder.AppendLine(line);
                }
            }
            return builder.ToString();
        }

        private void closelist(){
            string closer = "";
            isinlist = false;
            currentlevel = 0;
            while (openedPool.Count!=0){
                closer = openedPool.Pop();
                builder.Append(closer);
            }
        }

        private ListState getliststate(string line){
            var state = new ListState();
            var match = Regex.Match(line, @"\s(\s*)(\*|\#)\s([\s\S]+)");
            if(match.Success){
                state.islist = true;
                state.isordered = match.Groups[2].Value == "#";
                state.level = match.Groups[1].Length+1;
                state.rest = match.Groups[3].Value;
            }
            return state;
        }

        private class ListState{
            public bool islist;
            public bool isordered;
            public int level;
            public string rest;
        }
    }
}